package com.tangdi.production.mpcctp.controller;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tangdi.production.mpcctp.util.QRCodeUtils;

@Controller
public class QrcodeController {

	@RequestMapping("qrcode")
	public void qrCode(String content, HttpServletResponse response) {

		if (org.apache.commons.lang.StringUtils.isBlank(content)){
			content = "http://192.168.0.101:8080/qrcode-starter/routePay";
		}
		
        // 定义二维码参数
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符集
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 纠错级别
        hints.put(EncodeHintType.MARGIN, 2);// 空白

        try (
    		ServletOutputStream output = response.getOutputStream();
    		ByteArrayOutputStream byteOutput = QRCodeUtils.encodeIO(content, "present.png", true);
        ){
            response.setContentType("image/jpeg;charset=GB2312");
            
            output.write(byteOutput.toByteArray());
            
			output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	@RequestMapping("routePay")
	public String routePay(HttpServletRequest req, HttpServletResponse resp) throws Exception{

		String userAgent = req.getHeader("user-agent");
		if (userAgent != null && userAgent.contains("AlipayClient")) {
			System.out.println("来自支付宝");
		}else if (userAgent != null && userAgent.contains("MicroMessenger")) {
			System.out.println("来自微信");
			throw new Exception("暂不支持微信");
		}else{
			System.out.println("未知来源");
			throw new Exception("暂不支持...");
		}
		
		return "routePay";
	}
	
}
